/**
 * 快手店铺体验分数据port
 * 数据处理
 */

// import moment from "moment"

import type { PlasmoMessaging } from "@plasmohq/messaging"

// 数据记录
let scoreData = {}
// 校验总键数
let totalKeys = 0
// 键名列表
let keysList = []

// 初始化数据
const initData = () => {
  scoreData = {}
}

// 更新scoreData
const updateScoreData = (data: any) => {
  scoreData = {
    ...scoreData,
    ...data
  }
}

/*** 拦截数据处理器 ***/
// 获取数据单位
const valueUnit = (_txt) => {
  switch (_txt) {
    case "PERCENT":
      return "%"
    case "HOUR":
      return "小时"
    default:
      return ""
  }
}

// 顶层数据处理 api=getKwaishopScoreDetailV3
const topLevelDataInspect = (api: string, data: any) => {
  if (api !== "getStoreScoreHomeV4") return
  // 临时记录数据
  const _temp = {}
  // 数据处理
  const {
    // dimDataCardVOList: l1Data,
    // kwaishopDimVOList: l2Data,
    kwaishopDimScoreModuleInfoVOList: l3Data,
    radaTime
  } = data?.data || {}
  // 顶级数据(店铺体验分)
  const l0Data = data?.data?.storeScoreOverviewWithC?.scoreDisplay || {}
  const _l0Title = l0Data?.scoreTitle
  const _l0Value = l0Data?.score?.valueMap["${0}"]?.text?.text
  if(_l0Title && _l0Value){
    _temp[_l0Title] = _l0Value
  }
  // 日期获取
  const _dateValue = l0Data?.updateTime?.valueMap["${0}"]?.text?.text
  if(_dateValue){
    // 在字符串中，使用正则表达式提取年月日，格式为 YYYY-MM-DD
    const _dateRegTxt = _dateValue.match(/(\d{4})-(\d{2})-(\d{2})/)
    if (_dateRegTxt) {
      _temp["日期"] = _dateRegTxt[0]
    }
  }
  
  // 1级数据
  const l1Data = data?.data?.storeScoreOverviewWithC?.dimDataCardVOList || []
  // 顶级数据解释
  l1Data.forEach((item: any) =>{
    // 名称
    const _key = item?.title?.valueMap["${0}"]?.text?.text
    const _value = item?.data?.valueMap["${0}"]?.text?.text
    _temp[_key] = _value
  })

  // 二级数据
  const l2Data = data?.data?.indexDataCardListVo?.nsIndexDisplayGroups || []
  l2Data.forEach((item:any)=>{
    const _subList = item?.indexDataCardsVo?.cardsData || []
    _subList.forEach((subItem: any) => {
      const _key = subItem?.title?.valueMap["${0}"]?.tooltip?.text
      const _value = subItem?.data?.valueMap["${0}"]?.text?.text
      const _unit = subItem?.data?.valueMap["${2}"]?.text?.text || ''
      _temp[_key] = _value + _unit
    })
  })

  // 三级数据
  // if (l3Data) {
  //   l3Data.forEach((item: any) => {
  //     // 第三层数据列表
  //     const l3List = item?.kwaishopIndexCardVOList || []
  //     l3List.forEach((subItem: any) => {
  //       const { kwaishopDataCardVO: subData } = subItem
  //       const _unit = valueUnit(subData["valueType"])
  //       _temp[subData["title"]] = subData["value"] + _unit
  //     })
  //   })
  // }
  updateScoreData(_temp)
}
// 次级数据处理 api=getIndexAndMathByDimCodeV3
const subLevelDataInspect = (api: string, data: any) => {
  if (api !== "getIndexAndMathByDimCodeV4") return
  // 临时数据记录
  const _temp = {}
  const subData = data?.data?.indexScoreInfo || []
  subData.forEach((item: any) => {
    // 下级数据列表
    const dataList = item?.indexMathVO || []
    dataList.forEach((subItem: any) => {
      const _unit = valueUnit(subItem["valueType"]) || ''
      const _title = subItem?.label
      const _value = subItem?.value
      if (_value && _title !== "承诺及时发货率") {
        _temp[_title] = _value + _unit
      }
    })
  })
  updateScoreData(_temp)
}

// port handler
const handler: PlasmoMessaging.PortHandler = async (req, res) => {
  const { api, data, action } = req.body
  switch (action) {
    case "clear":
      // 清空数据
      initData()
      break
    case "setKeys":
      // 设置数据键值总量
      totalKeys = data?.count || 0
      keysList = data?.fields || []
      break
    case "inspect":
      // 轮询处理拦截数据
      const inspectors = [topLevelDataInspect, subLevelDataInspect]
      for (const inspector of inspectors) {
        inspector(api, data)
      }
      break
    default:
      break
  }
  // console.log("scoreData", scoreData)
  res.send({
    data: scoreData,
    keysList,
    rate: ((Object.keys(scoreData).length / totalKeys) * 100).toFixed(0)
  })
}

export default handler
